package guyubao.com.service.impl;

import guyubao.com.entity.vo.request.JDCertificateVoRequest;
import guyubao.com.service.RedisService;
import guyubao.com.utils.Const;
import javax.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author wxa
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    StringRedisTemplate stringRedisTemplate;

    /***
     * 添加到redis的邮箱验证码
     */
    @Override
    public void putEmailVerifyCode(String key, int value, long time){
        // 将验证码放入redis
        stringRedisTemplate.opsForValue()
                .set(Const.VERIFY_EMAIL_DATA+key,String.valueOf(value),time, TimeUnit.SECONDS);
    }

    /**
     * 移除Redis中存储的邮件验证码
     * @param email 电邮
     */
    @Override
    public void deleteEmailVerifyCode(String type, String email){
        String key = Const.VERIFY_EMAIL_DATA+type+":" + email;
        stringRedisTemplate.delete(key);
    }
    /**
     * 获取Redis中存储的邮件验证码
     * @param email 电邮
     * @return 验证码
     */
    @Override
    public String getEmailVerifyCode(String type, String email){
        String key = Const.VERIFY_EMAIL_DATA+type+":" + email;
        return stringRedisTemplate.opsForValue().get(key);
    }

    /***
     * 验证验证码
     */
    @Override
    public String verificationCode(String code, String type, String email) {
        if (code==null) {
            return "请输入验证码";
        }
        String redisCode = this.getEmailVerifyCode(type,email);
        if (redisCode==null) {
            return "请先获取验证码";
        }
        if (!code.equals(redisCode)){
            this.deleteEmailVerifyCode(type,email);
            return "验证码输入错误，请重新获取验证码";
        }
        this.deleteEmailVerifyCode(type,email);
        return null;
    }
    /***
     * 添加用户凭证
     */
    @Override
    public String addAccount(String id, String uuid, int expire){
        if (id==null||id.isEmpty()||uuid==null||uuid.isEmpty()||expire==0)return "参数不正确";
        stringRedisTemplate.opsForValue().set(Const.JWT_WHITE_LIST+id,uuid, 3600L * 24 * expire, TimeUnit.SECONDS);
        return null;
    }
    /***
     * 得到redis的值
     */
    @Override
    public String getValue(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }
    /***
     * 删除redis的值
     */
    @Override
    public Boolean delKey(String key){
        return stringRedisTemplate.delete(key);
    }
    /***
     * 删除用户凭证
     */
    public String deleteAccount(String id){
        if (id==null) return "参数不正确";
        stringRedisTemplate.delete(Const.JWT_WHITE_LIST + id);
        return null;
    }
}
